<!-- 数据list -->
<template>
  <div class="data-list">
    <div class="op">
      <el-button type="text" @click="teggleChoose()">全选/反选</el-button>
      <el-button type="text" @click="deleteChoose()">批量删除</el-button>
      <el-button type="text" @click="addWaterMarkChoose()">批量添加水印</el-button>
    </div>
    <div class="list">
      <div v-if="list.length === 0" class="no-data">暂无数据~~</div>
      <div v-else class="list-in">
        <div class="widthitem" v-for="item in list" :key="item.id">
          <div :class="{ item:true, active: selection.indexOf(item.id) > -1}">
            <div @click.stop="clickItem(item.id)"
              :class="{noselect:true,'item-content':true, cur:selection.indexOf(item.id) > -1}">
              <div class="img">
                <img :src="src(item.id)" />
              </div>
              <div class="tick" v-if="selection.indexOf(item.id) > -1">
                <i class="icon iconfont icon-duigou"></i>
              </div>
              <div class="operation">
                <div class="oli">
                  <el-button type="text" @click.stop="checkItem(item)"
                    v-if="item.type === 0 && item.originalFilename.substr(item.originalFilename.lastIndexOf('.')+1) !== 'ico'">
                    <i class="el-icon-zoom-in"></i>
                  </el-button>
                  <el-button type="text" @click.stop="checkItem(item)" v-if="item.type === 5">
                    <i class="el-icon-zoom-in"></i>
                  </el-button>
                  <el-button v-if="item.type !== 4" type="text" @click.stop="downItem(item.id)"><i
                      class="el-icon-download"></i>
                  </el-button>
                  <el-button type="text" @click.stop="editItemLabel(item.id)"><i class="el-icon-edit"></i></el-button>
                  <el-button type="text" @click.stop="deleteItem(item.id)"><i class="el-icon-delete"></i></el-button>
                </div>
              </div>
            </div>
            <el-tooltip class="item" effect="dark" :content="item.originalFilename" placement="top-start">
              <div class="title textnowrap" style="cursor:pointer;" @click.stop="setOname(item.id)">
                {{item.originalFilename}}
              </div>
            </el-tooltip>
            <div class="repertorydetail">
              <div class="size textnowrap">
                <div>类型: <span class="green">{{item.type | showtype}}</span></div>
                <div v-if="item.type !== 4">大小: <span class="green">{{item.size | showSize}}</span></div>
              </div>
              <div class="label textnowrap">
                <div>
                  标签:
                  <span v-if="item.labelId === 0" class="orange">未定义标签</span>
                  <!-- <span v-for="label in labelsFilter(item.labelId)" :key="label.id" class="orange">{{label.name}}</span> -->
                  <span v-for="label in labelsFilter(item.labelId)" :key="label.id" class="orange">
                    <span v-if="label.name.length < 15">{{label.name}}</span>
                    <el-tooltip v-else class="item" effect="dark" :content="label.name" placement="top-start">
                      <span>{{label.name}}</span>
                    </el-tooltip>
                  </span>
                </div>
              </div>
              <div class="uploadtime textnowrap">
                <div>
                  上传时间: {{item.createAt | dateformat('YYYY-MM-DD HH:mm')}}
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div style="clear:both;"></div>
    </div>
    <!-- 修改标签 -->
    <el-dialog title="编辑" :visible.sync="dialogFormVisible" width="640px">
      <el-form :model="currentRepertory" v-loading="labelLoading" @submit.native.prevent>
        <el-form-item label="资源名称" label-width="80px" style="margin-bottom:15px;" class="requireStar">
          <el-input v-model.trim="currentRepertory.originalFilename" autocomplete="off" size="medium"
            style="width:88%;"></el-input>
            <span>{{'.' + currentRepertory.suffix}}</span>
        </el-form-item>
        <el-form-item label="所属标签" label-width="80px" style="margin-bottom:0;">
          <el-select style="width:88%;" v-model="currentRepertory.labelId" placeholder="请选择标签" size="medium">
            <el-option label="未定义" :value="0"></el-option>
            <el-option v-for="item in labels" :key="item.id" :label="item.name" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false;labelLoading = false" size="small">取 消</el-button>
        <el-button type="primary" @click="submitEditLabel" :disabled="labelLoading" size="small">
          {{labelLoading?'Loading...':'确 定'}}
        </el-button>
      </div>
    </el-dialog>
    <EditRepertoryOname ref="editRepertoryOname" :getName="submitRepertoryOname" />
  </div>
</template>
<script>
import EditRepertoryOname from '@/components/main/user/repertory/dialog/EditRepertoryOname.vue'
import * as functions from '@/core/functions.js'

export default {
  props: {
    where: {
      type: Object
    },
    page: {
      type: Object
    },
    changeLoading: {
      type: Function
    },
    dataTotal: {
      type: Function
    }
  },
  created () {
    // 获取所有的标签
    this.$post('/repertory/all-label').then((response) => {
      this.labels = response
    })
  },
  data () {
    return {
      // 显示图片列表的数据
      list: [],
      // 点击选中的id
      selection: [],
      // 标签
      labels: [],
      // 修改标签弹窗
      dialogFormVisible: false,
      // 修改标签的当前资源
      currentRepertory: {},
      originalFilenameNew: '',
      // label加载
      labelLoading: false
    }
  },
  computed: {
    labelsFilter () {
      let _this = this
      return function (_labelId) {
        return _this.labels.filter(item => item.id === _labelId)
      }
    }
  },
  methods: {
    // 加载数据
    resetData () {
      let param = Object.assign({}, this.where, this.page)
      param.type = [param.type]
      this.changeLoading(true)
      this.$jpost('/repertory/find', param).then(response => {
        if (response && response.total > 0) {
          this.dataTotal(response.total)
          this.list = response.list
        } else {
          this.list = []
          this.dataTotal(0)
        }
        this.selection = []
        this.changeLoading(false)
      })
    },
    src (id) {
      let item
      for (let i in this.list) {
        if (this.list[i].id === id) {
          item = this.list[i]
          break
        }
      }
      if (!item) {
        return ''
      }
      if (item.type === 0) {
        return functions.getRepertoryImageSrc({ hostId: this.$store.state.host.id, repertoryId: id, suffix: item.suffix, type: item.type, link: item.link }) + '?' + new Date().getTime()
      } else {
        return functions.getRepertoryImageSrc({ hostId: this.$store.state.host.id, repertoryId: id, suffix: item.suffix, type: item.type, link: item.link })
      }
    },
    // 点击
    clickItem (id) {
      let item = getItem(id, this.list)
      if (!item) {
        return null
      }
      if (this.selection.indexOf(id) === -1) {
        this.selection.push(id)
      } else {
        this.selection = this.selection.filter((temp) => {
          return !(temp === id)
        })
      }
    },
    // 点击查看
    checkItem (item) {
      if (!item) {
        return ''
      }
      if (parseInt(item.type) === 0) {
        let id = item.id
        window.open(functions.getRepertoryImageSrc({ hostId: this.$store.state.host.id, repertoryId: id, suffix: item.suffix, type: item.type, link: item.link }))
      } else if (parseInt(item.type) === 5) {
        let id = item.id
        window.open(functions.getRepertoryVideoSrc({ hostId: this.$store.state.host.id, repertoryId: id, suffix: item.suffix }))
      }
    },
    // 修改标签
    editItemLabel (id) {
      let item = getItem(id, this.list)
      if (!item) {
        return null
      }
      this.dialogFormVisible = true
      this.currentRepertory = JSON.parse(JSON.stringify(item))
      if (this.currentRepertory.originalFilename && this.currentRepertory.originalFilename.lastIndexOf('.') !== -1) {
        this.currentRepertory.originalFilename = this.currentRepertory.originalFilename.substring(0, this.currentRepertory.originalFilename.lastIndexOf('.'))
      } else {
        this.currentRepertory.originalFilename = this.currentRepertory.originalFilename
      }
    },
    // 提交修改标签
    submitEditLabel () {
      let item = getItem(this.currentRepertory.id, this.list)
      if (!item) {
        return null
      }
      if (this.labelLoading) {
        return
      }
      if (!this.currentRepertory) {
        return
      }
      if (!this.currentRepertory.originalFilename) {
        this.$message.error('资源名称不能为空！')
        return
      } else if (this.currentRepertory.originalFilename.length > 100) {
        this.$message.error('资源名称不能超过100个字！')
        return
      } else {
        let regx = /^[\u4e00-\u9fa50-9A-Za-z][\u4e00-\u9fa50-9A-Za-z@_.]*$/
        if (!regx.test(this.currentRepertory.originalFilename)) {
          this.$message.error('资源名称不能带特殊字符（除@_.外，且@_.不能作为开头）或空格！')
          return
        }
      }
      let param = {
        id: this.currentRepertory.id,
        labelId: this.currentRepertory.labelId
      }
      // 定义修改标签的方法
      const updateLabel = () => {
        if (item.labelId === param.labelId) {
          this.labelLoading = false
          this.dialogFormVisible = false
        } else {
          this.$post('/repertory/update-label', param).then((response) => {
            if (response && response.id) {
              let index = this.list.findIndex((item) => {
                return item.id === response.id
              })
              this.list.splice(index, 1, response)
              this.dialogFormVisible = false
              this.currentRepertory = {}
            }
            this.labelLoading = false
          })
        }
      }

      // 开始请求
      this.originalFilenameNew = ''
      if (this.currentRepertory.suffix) {
        this.originalFilenameNew = this.currentRepertory.originalFilename + '.' + this.currentRepertory.suffix
      } else {
        this.originalFilenameNew = this.currentRepertory.originalFilename
      }
      this.labelLoading = true
      if (item.originalFilename === this.originalFilenameNew) {
        updateLabel()
      } else {
        let updateRepertoryOname = {
          id: this.currentRepertory.id,
          name: item.originalFilename,
          oname: this.originalFilenameNew
        }
        this.$post('/repertory/update-repertory-oname', updateRepertoryOname).then(response => {
          if (response && response.id > 0) {
            this.list.forEach(element => {
              if (element.id === this.currentRepertory.id) {
                element.originalFilename = this.originalFilenameNew
              }
            })
            updateLabel()
          } else {
            this.labelLoading = false
          }
        })
      }
    },
    // 点击下载
    downItem (id) {
      let item = getItem(id, this.list)
      if (!item) {
        return ''
      }
      window.open(functions.getRepertoryDownloadHref(this.$store.state.host.id, id, item.suffix))
    },
    // 设置 oname 弹窗
    setOname (id) {
      let item = getItem(id, this.list)
      if (!item) {
        return ''
      }
      this.$refs['editRepertoryOname'].open(item)
    },
    // 提交更新oname
    submitRepertoryOname (id, name, callback) {
      let item = getItem(id, this.list)
      if (!item) {
        return
      }
      if (!name) {
        return
      }
      if (item.originalFilename === name) {
        if (typeof callback === 'function') {
          callback(item)
        }
        return
      }
      this.$post('/repertory/update-repertory-oname', { id: id, name: item.originalFilename, oname: name }).then(response => {
        if (response && response.id > 0) {
          this.list.forEach(element => {
            if (element.id === id) {
              element.originalFilename = name
            }
          })
        }
        if (typeof callback === 'function') {
          callback(response)
        }
      })
    },
    // 单个删除
    deleteItem (id) {
      let item = getItem(id, this.list)
      if (!item) {
        return
      }
      this.$confirm('确认删除 ' + item.originalFilename + '？', '提示', {
        confirmButtonText: '确定',
        type: 'warning'
      }).then(() => {
        this.$post('/repertory/delete', { id: id }).then((response) => {
          if (response && response.id && parseInt(response.id) > 0) {
            this.resetData()
          }
        })
      }).catch(() => {
      })
    },
    // 全选，反选
    teggleChoose () {
      if (this.selection.length !== this.list.length) {
        this.selection = []
        for (let i in this.list) {
          this.selection.push(this.list[i].id)
        }
      } else {
        this.selection = []
      }
    },
    // 批量删除
    deleteChoose () {
      if (!this.selection.length) {
        this.$message({ message: '未选中任何资源内容', type: 'error' })
        return
      }
      this.$confirm('确认删除选中的这' + this.selection.length + '个资源吗？', '提示', {
        confirmButtonText: '确定',
        type: 'warning'
      }).then(() => {
        this.$jpost('/repertory/delete-list', JSON.parse(JSON.stringify(this.selection))).then(response => {
          if (response && response.length > 0) {
            this.resetData()
            this.selection = []
          }
        })
      }).catch(() => {
      })
    },
    // 批量添加水印
    addWaterMarkChoose () {
      let noAddFilename = ''
      this.selection = this.selection.filter((temp) => {
        for (let i in this.list) {
          if (this.list[i].id === temp) {
            if (this.list[i].type === 0) {
              return temp
            } else {
              if (noAddFilename) {
                noAddFilename += ', ' + this.list[i].originalFilename
              } else {
                noAddFilename += this.list[i].originalFilename
              }
            }
            break
          }
        }
      })
      if (noAddFilename) {
        if (!this.selection.length) {
          this.$message({ message: '仅支持本地图片资源文件添加，当前您未选中任何资源内容', type: 'error' })
          return
        }
      } else {
        if (!this.selection.length) {
          this.$message({ message: '未选中任何资源内容', type: 'error' })
          return
        }
      }
      this.$confirm(`仅支持本地图片资源文件添加，<span style="color:#cc0000; font-size:15px;">水印添加后不可撤销</span>，是否添加水印？`, '确认添加水印', {
        confirmButtonText: '确定',
        type: 'warning',
        dangerouslyUseHTMLString: true
      }).then(() => {
        this.$jpost('/watermark/repertory-mark', JSON.parse(JSON.stringify(this.selection))).then(response => {
          if (response) {
            this.resetData()
            this.selection = []
          }
        })
      }).catch(() => {
      })
    }
  },
  components: {
    EditRepertoryOname
  },
  filters: {
    showSize: function (value) {
      if (value < 1024) {
        return value + 'b'
      } else if (value < 1024 * 1024) {
        return parseFloat(value / 1024).toFixed(1) + 'Kb'
      } else {
        return parseFloat(value / (1024 * 1024)).toFixed(1) + 'Mb'
      }
    },
    showtype: function (type) {
      if (type === 0) {
        return '图片'
      } else if (type === 1) {
        return '文件'
      } else if (type === 2) {
        return 'Flash'
      } else if (type === 3) {
        return '音频'
      } else if (type === 4) {
        return '外链图片'
      } else if (type === 5) {
        return '视频'
      } else if (type === 6) {
        return 'SSL文件'
      }
    }
  }
}

function getItem (id, list) {
  let item
  for (let i in list) {
    if (list[i].id === id) {
      item = list[i]
      break
    }
  }
  return item
}

</script>

<style scoped>
.data-list .op {
  padding-left: 20px;
}
.data-list .list {
  overflow-x: auto;
  width: 100%;
}
.data-list .list .list-in {
  display: flex;
  flex-wrap: wrap;
  padding: 0 10px;
  min-height: 300px;
  min-width: 1250px;
}
.data-list .list .widthitem {
  width: 16.66%;
  padding: 0 6px;
}
.data-list .list .no-data {
  width: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 18px;
  color: #888888;
  height: 200px;
}
.data-list .list .item {
  margin-bottom: 24px;
}
.data-list .list .item .item-content {
  text-align: center;
  border: 1px solid #e5e5e5;
  background-color: #eeeeee;
  margin-bottom: 10px;
  position: relative;
}

.data-list .list .item .cur {
  border-color: #409eff;
}
.data-list .list .item .item-content:hover {
  border-color: #409eff;
}
.data-list .list .item .item-content .img {
  line-height: 180px;
  padding: 10px;
  height: 200px;
}
.data-list .list .item .repertorydetail {
  line-height: 1.5;
}
.data-list .list .item .size {
  text-align: right;
  color: rgb(51, 51, 51);
  font-size: 13px;
  display: flex;
  justify-content: space-between;
}
.data-list .list .item .label {
  text-align: right;
  color: rgb(51, 51, 51);
  font-size: 11px;
  display: flex;
  justify-content: space-between;
}
.data-list .list .item .uploadtime {
  text-align: left;
  color: rgb(51, 51, 51);
  font-size: 11px;
}
.data-list .list .item .title {
  color: rgb(51, 51, 51);
  font-size: 14px;
  margin: 8px 0;
}
.data-list .list .item .item-content .img img {
  max-height: 100%;
  max-width: 100%;
  vertical-align: middle;
}
.data-list .list .item .item-content .tick {
  position: absolute;
  top: 4px;
  left: 4px;
  text-align: left;
  height: 0px;
}
.data-list .list .item .item-content .tick .icon {
  display: inline-block;
  border-radius: 100%;
  background-color: #409eff;
  color: #ffffff;
  padding: 2px;
}
.data-list .list .item .item-content .operation {
  position: absolute;
  z-index: 1;
  top: 0;
  right: 0;
  text-align: right;
  padding: 0 10px;
  background: #409eff;
  opacity: 0;
}
.data-list .list .item .item-content:hover .operation {
  opacity: 1;
}
.data-list .list .item .item-content .operation .el-button--text {
  color: #fff;
  padding: 8px 4px;
  font-size: 16px;
}
.data-list .list .item .item-content .operation .el-button + .el-button {
  margin-left: 5px;
}
.requireStar /deep/ .el-form-item__label:before {
  content: '*';
  color: #f56c6c;
  margin-right: 4px;
}
</style>
